package com.gb.web.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;

import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 文件处理工具类
 */
public class FileUtils {
    /**
     * 读取json文件，返回json串
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static String parseJSON(String fileName,String city,String codeStr) {
		String path = FileUtils.class.getClassLoader().getResource(fileName).getPath();
        String s = FileUtils.readJsonFile(path);
        JSONObject jobj = JSON.parseObject(s);
        JSONArray citys = jobj.getJSONArray(city);
        for (int i = 0 ; i < citys.size();i++){
            JSONObject key1 = (JSONObject)citys.get(i);
            String code = (String)key1.get("code");
            String name = (String)key1.get("name");
            if(codeStr.equals(code)){
            	 return name;
            }
        }
		return "";
	}
    
    
    public String parseJSONFile(String fileName,String type,String codeStr) throws IOException {
		InputStream inputStream = this.getClass().getResourceAsStream(fileName);
		String path = inputStream2Str(inputStream);
        String s = FileUtils.readJsonFile(path);
        JSONObject jobj = JSON.parseObject(s);
        JSONArray citys = jobj.getJSONArray(type);
        for (int i = 0 ; i < citys.size();i++){
            JSONObject key1 = (JSONObject)citys.get(i);
            String code = (String)key1.get("code");
            String name = (String)key1.get("name");
            if(codeStr.equals(code)){
            	 return name;
            }
        }
		return "";
	}
    
    /**
     * 获取inputStream转String
     */
    private static String inputStream2Str(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        return sb.toString();
    }
    
    
    
	public static String getCardDetail(String cardNo) {
		// 创建HttpClient实例
		String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo="+cardNo+"&cardBinCheck=true";
		StringBuilder sb = new StringBuilder();
		try {
			URL urlObject = new URL(url);
			URLConnection uc = urlObject.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				sb.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	 /**
     * 将文件名解析成文件的上传路径
     */
    public static File upload(MultipartFile file, String filePath) {
        //String name = getFileNameNoEx(file.getOriginalFilename());
        String suffix = getExtensionName(file.getOriginalFilename());
        StringBuffer nowStr = fileRename();
        try {
            String fileName = nowStr + "." + suffix;
            String path = filePath + fileName;
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(path).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(dest);
            return dest;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	/**
	 * 根据key 获取本地配置
	 * @param key
	 * @return
	 */
	public static String getStringByKey(String key, String properties) {
		try {
			InputStream inputStream = new FileInputStream(properties);
			Properties p = new Properties();
			p.load(inputStream);
			String str = p.getProperty(key);
			p.clear();
			inputStream.close();
			return str;
		} catch (MissingResourceException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
    
    /**
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception{
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }
    
    /**
     * MultipartFile转File
     */
    public static File toFile(MultipartFile multipartFile){
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix="."+getExtensionName(fileName);
        File file = null;
        try {
            // 用uuid作为文件名，防止生成的临时文件重复
            file = File.createTempFile(simpleUUID(), prefix);
            // MultipartFile to File
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    
    /**
     * 获取文件扩展名，不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 上传文件重命名
     * @return 新的文件名
     */
    public static StringBuffer fileRename() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        StringBuffer buf = new StringBuffer(time);
        Random r = new Random();
        //循环取得三个不大于10的随机整数
        for (int x = 0; x < 3; x++) {
            buf.append(r.nextInt(10));
        }
        return buf;
    }

    /**
	 * 简化的UUID，去掉了横线
	 */
	public static String simpleUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	/**
	 * 如果文件不存在则创建
	 * @param path
	 */
	public static void crateNotExists(String path) {
		File f = new File(path);
		try {
			if (!f.getParentFile().exists()) { // 判断父目录路径是否存在，即test.txt前的I:\a\b\
				f.getParentFile().mkdirs(); // 不存在则创建父目录
			}
			if (!f.exists()) {
				f.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 以行为单位读取文件，常用于读取面向行的格式化文件
	 * @param path
	 * @return
	 */
	public static String readByLines(String path) {
		String content = null;
		try {
			crateNotExists(path);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
			StringBuffer sb = new StringBuffer();
			String temp = null;
			while ((temp = bufferedReader.readLine()) != null) {
				sb.append(temp);
			}
			content = sb.toString();
			bufferedReader.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	public static String readFile(File file, String charset) {
		if (charset == null) {
			charset = "UTF-8";
		}
		if (file.isFile() && file.exists()) {
			try {
				FileInputStream fileInputStream = new FileInputStream(file);
				InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charset);
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				StringBuffer sb = new StringBuffer();
				String text = null;
				while ((text = bufferedReader.readLine()) != null) {
					sb.append(text + " ");
				}
				return sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

    
    public static void main(String[] args) {
    	String provinceName=FileUtils.parseJSON("city/json-array-of-province.json","province","440000");
    	System.out.println(provinceName);
    	String cityName=FileUtils.parseJSON("city/json-array-of-city.json","city","440300");
    	System.out.println(cityName);
    	System.out.println(getCardDetail("6217214000029981821"));
	}
}
